/*
 *  Copyright (C) 2011 JiangHongTiao <jjurco.sk_gmail.com>
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package sk.lieskove301.jianghongtiao.math.statistic.distributions;

/**
 * Date of create: May 15, 2011
 *
 * @author JiangHongTiao <jjurco.sk_gmail.com>
 * @version 2011.0515
 */
public class TriangularDistribution implements Distribution {

    private int min = 0;
    private int max = 1;

    public TriangularDistribution() {
    }

    public String getName() {
        return "Triangular Distribution";
    }

    public String getLetter() {
        return "T";
    }

    /**
     *
     * @param double x (required)
     * @param double min (optional, if not present used default=0)
     * @param double max (optional, if not present used default=1)
     * @return 
     */
    public double cdf(double... attr) throws IllegalArgumentException {
        if((attr == null) || (attr.length == 0) || (attr.length > 3)){
            throw new IllegalArgumentException("invalid number of arguments");
        }
        double minA = min;
        double maxB = max;
        double x = attr[0];
        if(attr.length > 1){
            minA = attr[1];
        }
        if(attr.length >2){
            maxB = attr[2];
        }
        if(x < (minA+maxB)/2){
            return (2.0 * Math.pow(minA-x, 2))/Math.pow(minA-maxB, 2);
        }
        if(x > maxB) {
            return 1;
        }
        return (-2.0* maxB * minA + 4*maxB*x - maxB*maxB + minA*minA -2.0*x*x)/
                (Math.pow(minA-maxB, 2));
    }

    public double randomNumber() {
        return cern.jet.random.Distributions.nextTriangular(new cern.jet.random.engine.MersenneTwister(new java.util.Date()));
    }

    public double randomCdf() {
        return cdf(randomNumber());
    }

}
